package com.shujia.flink.tf

import org.apache.flink.api.common.functions.ReduceFunction
import org.apache.flink.streaming.api.scala._

object Demo6Reduce {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val kvDS: DataStream[(String, Int)] = linesDS
      .flatMap(_.split(","))
      .map((_, 1))

    val keyByDS: KeyedStream[(String, Int), String] = kvDS.keyBy(_._1)

    /**
     * reduce: keyBy之后对数据聚合计算
     * x和y的第一个元素是一样的，只对value做聚合
     */
    val reduceDS: DataStream[(String, Int)] = keyByDS.reduce((x, y) => (x._1, x._2 + y._2))

    //reduceDS.print()


    //java api
    val javaDS: DataStream[(String, Int)] = keyByDS.reduce(new ReduceFunction[(String, Int)] {
      override def reduce(x: (String, Int), y: (String, Int)): (String, Int) = {
        (x._1, x._2 + y._2)
      }
    })

    javaDS.print()

    env.execute()
  }

}
